package common;

import java.io.*; // File, IOException
import javax.xml.parsers.*; // DocumentBuilder, DocumentBuilderFactory, ParserConfigurationException
import org.w3c.dom.*; // Document, NamedNodeMap, Node, NodeList
import org.xml.sax.*;
import java.net.*;
import java.util.*;

public class XmlParserLogin {	

    private DocumentBuilderFactory dbf;
    private DocumentBuilder db;
    private Document document;
    
    public XmlParserLogin(){      
      init(); // 초기화
      //getDocument(urlString); // xml 파일을 읽어들임
      // xml 파일을 출력, "words" : xml 내의 엘리먼트 중 하나, "voca" : 속성이름
      //getXmlValue("item", "name");
    }
    
    public void init(){
        dbf = DocumentBuilderFactory.newInstance(); // 인스턴스를 할당
        try{ db = dbf.newDocumentBuilder(); } catch(Exception e){} // ParserConfigurationException
    }

    public void getDocument(String urlString ) {
       try {
         URL url = new URL( urlString );

           try {
             URLConnection URLconnection =   url.openConnection ( ) ;
             URLconnection.setConnectTimeout(2000);
             HttpURLConnection httpConnection =  (HttpURLConnection)URLconnection;

             int responseCode =  httpConnection.getResponseCode ( ) ;
             if ( responseCode == HttpURLConnection.HTTP_OK) {
                 InputStream in = httpConnection.getInputStream ( ) ;

                 try {
                   document = db.parse( in );                 
                 } catch(org.xml.sax.SAXException e ) {
                      e.printStackTrace ( ) ;
                 }
              } else {
                  System.out.println( "HTTP connection response !=  HTTP_OK" );

              }
           } catch ( IOException e ) {
                e.printStackTrace ( ) ;
           } // Catch
        } catch ( MalformedURLException e ) {
            e.printStackTrace ( ) ;
      } // Catch
    } // getDocument

    public String getXmlValue(String elementName, String attrName){
    	String noeValue="";
    	
    	if(document != null){ // 문서가 비어있지 않은 경우
            
	         NodeList list = document.getElementsByTagName(elementName);
	        
	         Node node = list.item(0); // 엘리먼트 이름이 elementName인 노드를 차례대로 반환(type. Node)
	         NamedNodeMap attrs = node.getAttributes(); // elementName의 속성들을 반환(type. Node)
	         Node value = attrs.getNamedItem(attrName);
	         
	         
	         noeValue = value.getNodeValue().toString();
	          
        }else{
        	System.out.println("xml 문서가 비었습니다.");
        }
    	
    	return noeValue;   
     }
}
